package com.hh.game.service.gateway.filter.ip;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.SocketAddress;

/**
 *
 */
public class RateLimitFilter extends ChannelInboundHandlerAdapter {
    private int limit;
    private int blackLimit;
    private long timer;
    private int count;

    public RateLimitFilter(int limit ,int blackLimit) {
        this.limit = limit;
        this.blackLimit = blackLimit;
        this.timer = 0L;
        this.count = 0;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        long now = System.currentTimeMillis();
        if(now - timer > 1000){
            this.count = 0;
            this.timer = now;
        }
        this.count++;
        if(this.count > this.limit){
            SocketAddress address = ctx.channel().remoteAddress();
            if (address != null) {
                String ip = address.toString().split(":")[0];
                int count = IPContainer.addOutQpsCloseIP(ip);
                if (blackLimit < count) {
                    IPContainer.addBlackIP(ip);
                }
            }
            ctx.close();
        }else {
            super.channelRead(ctx, msg);
        }

    }
}
